package com.xjuse.yida.commom.gaode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Desc  高德地图 IP地址定位服务
 * @Author 嗜雪的蚂蚁
 * @Date 2022/10/25 1:58
 **/
@Component
@Slf4j
public class GaodeIpServiceUtil {
    @Autowired
    private final RestTemplate restTemplate;

    //高德应用appKey
    private static final String appKey = "9ecbd556fed16b621ee86dc931d94fe8";
    //高德定位接口地址
    private static final String ipLocationUrl = "https://restapi.amap.com/v3/ip?key={key}&ip={ip}";

    public GaodeIpServiceUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /***
     * @Description  获取用户当前IP地址
     * @author 嗜雪的蚂蚁
     **/
    public static String getUserIp(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }
        if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (String ip1 : ips) {
                if (!("unknown".equalsIgnoreCase(ip1))) {
                    ip = ip1;
                    break;
                }
            }
        }
        return ip;
    }

    public LinkedHashMap<String,Object> getUserLocation(String ip) {
        Map<String, String> params = new HashMap<>();
        params.put("key", appKey);
        params.put("ip", ip);
        ResponseEntity<LinkedHashMap> result = restTemplate.getForEntity(ipLocationUrl, LinkedHashMap.class, params);
        if (result.getBody() == null) {
            return null;
        }
        log.info("IP地址{}获取到的地址响应信息为:{}",ip,result.toString());
        return result.getBody();
    }


}
